﻿using Windows.UI.Xaml.Controls;

namespace Sidvall.UI.Uwp.Views
{
    public class ContentControlRegionManager : Sidvall.UI.Views.IRegionManager
    {
        #region Public Members

        public object GetRegionContainer(object container, string regionName)
        {
            Windows.UI.Xaml.Controls.ContentControl regionControl;

            regionControl = GetRegionControl(container, regionName);
            if (regionControl == null)
                return null;
            return regionControl.Content;
        }
        public object[] GetViews(object container, string regionName)
        {
            Windows.UI.Xaml.Controls.ContentControl regionControl;

            regionControl = GetRegionControl(container, regionName);
            if (regionControl == null)
                return null;
            if (regionControl.Content == null)
                return null;
            return new object[] { regionControl.Content };
        }
        public bool RemoveView(object container, string regionName)
        {
            Windows.UI.Xaml.Controls.ContentControl regionControl;

            regionControl = GetRegionControl(container, regionName);
            if (regionControl == null)
                return false;
            regionControl.Content = null;

            return true;
        }
        public bool ShowView(object container, string regionName, object view)
        {
            Windows.UI.Xaml.Controls.ContentControl regionControl;

            regionControl = GetRegionControl(container, regionName);
            if (regionControl == null)
                return false;
            regionControl.Content = view;
            return true;
        }
        public bool CanShowView(object container, string regionName)
        {
            Windows.UI.Xaml.Controls.ContentControl regionControl;

            regionControl = GetRegionControl(container, regionName);
            if (regionControl == null)
                return false;
            return true;
        }

        #endregion
        #region Private Members

        private static Windows.UI.Xaml.Controls.ContentControl GetRegionControl(object container, string regionName)
        {
            var window = container as Windows.UI.Xaml.Window;
            if (window != null)
            {
                var frame = window.Content as Frame;
                return frame.FindName(regionName) as Windows.UI.Xaml.Controls.ContentControl;
            }
            else
            {
                var element = container as Windows.UI.Xaml.FrameworkElement;
                if (element == null)
                    return null;
                return element.FindName(regionName) as Windows.UI.Xaml.Controls.ContentControl;
            }
        }

        #endregion
    }
}
